summaryrefslogtreecommitdiff
path: root/js/lost.js
blob: 133dfaccc5959693a1e29f633584ee6ad0681974 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
"use strict";
// It's strict!

//
// Helper functions
//

// Return the id for the opposite direction of the direction given.
function oppositeDir( iDir )
{
    if( iDir%2 === 1 )
        return iDir-1;
    return iDir+1;
}

/**
 * Create a new button element using the dom that has the given label,
 * and calls the movePlayer method on the given map, along the provided
 * dimension, and in the specified direction.
 *
 * The button created is then returned.
 */
function createMoveButton( rMazeMap, iDim, iDir, sLabel )
{
    let btn = document.createElement('button');
    btn.addEventListener(
        'click',
        MazeMap.prototype.movePlayer.bind(
            rMazeMap,
            iDim,
            iDir
            )
        );
    if( sLabel === null || sLabel === '' )
    {
        btn.appendChild(
            document.createTextNode('Dim ' + (j+1) + ': -')
            );
    }
    else
    {
        btn.appendChild(
            document.createTextNode( sLabel )
            );
    }
    return btn;
}

/**
 * Class: RandomLcg
 *
 * This implements a Linear Congruential Generator PRNG. Is this the best
 * PRNG? Nope! Is it decently random for our purposes, sure.
 *
 * Why was this implemented? I wanted to be able to share mazes, in order to
 * do that we needed two things that we can't get from JS by default:
 *  1. To be able to set the seed (and get it if possible).
 *  2. To be sure that the same algorithm would be used on every version of
 *     every browser.
 * 
 * Unfortunately JavaScript doesn't gurantee either of these things, so
 * instead of writing a CMWC and using a bunch of memory I just used the
 * settings from the glibc random function and here we are.
 *
 * @constructor
 */
function RandomLcg()
{
    // Current state
    this.iState = 0;

    // Initial seed, remember this so we can display it easily later.
    this.iSeed = 0;

    // Set the seed randomly to start.
    this.inventSeed();
}

//
// Replace the current seed and reset the state.
//
RandomLcg.prototype.setSeed = function setSeed( iSeed )
{
    this.iState = this.iSeed = iSeed;
}

//
// Get the seed that was initially used on this random number generator.
//
RandomLcg.prototype.getSeed = function getSeed()
{
    return this.iSeed;
}

//
// Make up a seed.
//
RandomLcg.prototype.inventSeed = function inventSeed()
{
    // Based on my reading it's safest to assume that we can get 16 bits worth
    // of random data reliably.  Let's build a 32 bit number from two 16 bit
    // numbers.
    this.setSeed(
        (Math.floor(Math.random()*0xffff)) |
        (Math.floor(Math.random()*0xffff)<<16)
        );
}

//
// Get us a random number between 0 and 1.0, exclusive of the upper bound.
//
RandomLcg.prototype.random = function random()
{
    this.iState = ((this.iState * 1103515245) + 12345) & 0x7fffffff;
    return this.iState/(0x7fffffff+1);
}

//
// Get us a random integer between 0 and max, exclusive of the upper bound.
//
RandomLcg.prototype.randInt = function randInt( max )
{
    return Math.floor(this.random() * max);
}

// Lets just build a shared prng object to use all over.
let lRand = new RandomLcg();

/**
 * Class: Signal
 *
 * Super simple implementation of a signal/slot concept.  I didn't need most of
 * the features, so this just lets us connect 0-parameter functions and call
 * them en-masse whenever the signal is fired.
 *
 * @constructor
 */
function Signal()
{
    this.aSlot = new Array();
}

//
// Connect this signal to a new slot (function to call). I recommend using bind
// to create valid object-function references that have state supposed to
// disembodied functions.
//
Signal.prototype.connect = function connect( fSlot )
{
    this.aSlot.push( fSlot );
}

//
// Trigger the signal, and notify all slots bound to this signal.
//
Signal.prototype.emit = function emit()
{
    for( let j = 0; j < this.aSlot.length; j++ )
    {
        (this.aSlot[j])();
    }
}

/**
 * Class: Cell
 *
 * Simple container that tracks info about a cell in the maze.
 *
 * @constructor
 */
function Cell()
{
    this.iDist = 0;
    this.iPath = 0;
    this.iWalls = 0;
}

/**
 * Class: Position
 *
 * A simple class that keeps track of coordinates in N-dimensional space.
 * That's really just an array of numbers with N spaces in it.
 *
 * @constructor
 */
function Position( iDims, Vals )
{
    if( typeof iDims === 'string' )
    {
        let sChunks = iDims.split(',');
        this.iDims = sChunks.length;
        this.aiValues = new Array(this.iDims);
        for( let j = 0; j < this.iDims; j++ )
        {
            this.aiValues[j] = parseInt( sChunks[j].trim(), 10 );
        }
    }
    else
    {
        // Store dimension count
        this.iDims = iDims;

        // Check to see if Vals is a non-empty array
        if( Array.isArray(Vals) && Vals.length > 0 )
        {
            // Make sure Vals has the right number of elements
            if( Vals.length != iDims )
            {
                throw new Error(
                    'Position must be initialized with no dimensional data, '+
                    'or the correct number of elements.');
            }
            
            // If it does have the correct number of elements, just
            // use it instead of creating a new array
            this.aiValues = Vals;
        }
        else
        {
            // We don't have values from the constructor, let's just
            // create a new blank one...
            this.aiValues = new Array( this.iDims );

            // ...and set the position to zero in all dimensions.
            for( let j = 0; j < this.iDims; j++ )
            {
                this.aiValues[j] = 0;
            }
        }
    }
}

//
// Get the number of dimensions defined in this position.
//
Position.prototype.getDims = function getDims()
{
    return this.iDims;
}

//
// Get the value of one dimension of the coordinate in this position.
//
Position.prototype.get = function get( iDim )
{
    return this.aiValues[iDim];
}

//
// Set the value of one dimension of the coordinate in this position.
// This modifies the position in place.
//
Position.prototype.set = function set( iDim, iVal )
{
    this.aiValues[iDim] = iVal;
}

//
// Apply a delta to the specified dimension in the current position.
// This modifies the position in place.
//
Position.prototype.add = function add( iDim, iDelta )
{
    this.aiValues[iDim] += iDelta;
    return this.aiValues[iDim];
}

//
// Copy the current position object and return one with a modified value in
// the specified dimension.
//
Position.prototype.translate = function translate( iDim, iDelta )
{
    let tmp = new Position( this.iDims, this.aiValues.slice() );
    tmp.add( iDim, iDelta );
    return tmp;
}

//
// Return an exact copy of this position object.
//
Position.prototype.copy = function translate()
{
    return new Position( this.iDims, this.aiValues.slice() );
}

//
// Compare two position objects for equality.  Return true if they are the same,
// false otherwise.
//
Position.prototype.equals = function equals( rhs )
{
    if( this.iDims != rhs.iDims &&
        this.aiValues.length != rhs.aiValues.length )
        return false;

    for( let j = 0; j < this.aiValues.length; j++ )
    {
        if( this.aiValues[j] != rhs.aiValues[j] )
            return false;
    }

    return true;
}

//
// Converts the position to a nicely formatted string of numbers.
//
Position.prototype.toString = function toString()
{
    let ret = this.aiValues[0].toString();
    for( let j = 1; j < this.aiValues.length; j++ )
    {
        ret += ',' + this.aiValues[j].toString();
    }

    return ret;
}

/**
 * Class: MazeMap
 *
 * The maze itself.  This doesn't do a whole lot on it's own except track data
 * and manage the player position and worms.  The worms do the real work of
 * generating a maze.
 *
 * @constructor
 */
function MazeMap( Dimensions )
{
    // Store dimensional data
    this.Dimensions = Dimensions;
    this.aWorms = new Array();
    this.pPlayer = null;
    this.pGoal = null;
    this.ePlayerMoved = new Signal();
    this.eVictory = new Signal();
    this.ePlayerSetup = new Signal();

    // Compute the total number of cells
    let iTotalSize = 1;
    for( let j = 0; j < Dimensions.getDims(); j++ )
    {
        iTotalSize *= Dimensions.get( j );
    }

    // Allocate cell array, and initialize cells
    this.aCell = new Array( iTotalSize );
    for( let j = 0; j < iTotalSize; j++ )
    {
        this.aCell[j] = new Cell();
    }
}

//
// Get the number of dimensions in this maze.
//
MazeMap.prototype.getDims = function getDims()
{
    return this.Dimensions.getDims();
}

//
// Get the size of the specified dimension.
//
MazeMap.prototype.getSize = function getSize( iDim )
{
    return this.Dimensions.get( iDim );
}

//
// Get a reference to the current player position in the maze.
//
MazeMap.prototype.getPlayerPos = function getPlayerPos()
{
    return this.pPlayer;
}

//
// Replace the player position with a new position.
//
MazeMap.prototype.setPlayerPos = function setPlayerPos( pNewPos )
{
    this.pPlayer = pNewPos;
    this.ePlayerMoved.emit();
}

//
// Move the player the specified amount (iDelta) along the specified dimension
// (iDim).  This takes walls and maze borders into account, and will not move
// the player in an "illegal" way.
//
MazeMap.prototype.movePlayer = function movePlayer( iDim, iDelta )
{
    let cCur = this.get( this.pPlayer );

    let iBit = iDim*2;
    if( iDelta > 0 )
        iBit++;

    if( (cCur.iWalls&(1<<iBit)) === 0 )
        return;

    let iNewX = this.pPlayer.get( iDim ) + iDelta;
    if( iNewX < 0 || iNewX >= this.getSize( iDim ) )
        return;

    this.pPlayer.add( iDim, iDelta );
    this.ePlayerMoved.emit();

    if( this.pPlayer.equals( this.pGoal ) )
    {
        this.eVictory.emit();
    }
}

//
// Helper that determines if the provided position is inside the maze or not.
//
MazeMap.prototype.isInside = function isInside( Position )
{
    if( Position.getDims() != this.Dimensions.getDims() )
    {
        throw new Error(
            'Number of dimensions in map and position do not match.'
            );
    }

    for( let j = 0; j < this.getDims(); j++ )
    {
        if( Position.get( j ) < 0 )
            return false;
        if( Position.get( j ) >= this.Dimensions.get( j ) )
            return false;
    }

    return true;
}

//
// Internal helper function.  This converts from a Position object to an array
// index, effectively flattening an arbitrarily dimensional coordinate into a
// one dimensional array coordinate.  This is used to find the actual storage
// location of cells internally.
//
MazeMap.prototype.getIndex = function getIndex( Position )
{
    if( !this.isInside( Position ) )
    {
        throw new Error('Position is outside of map.');
    }

    let iIdx = 0;
    let iScale = 1;
    for( let j = 0; j < this.getDims(); j++ )
    {
        iIdx += Position.get( j ) * iScale;
        iScale *= this.Dimensions.get( j );
    }
    return iIdx;
}

//
// Get a cell at the given Position.
//
MazeMap.prototype.get = function get( Position )
{
    return this.aCell[this.getIndex( Position )];
}

//
// Create a new worm and add it to the maze.  Specify the starting position
// and the loop chance (betweer 0.0 and 1.0).  This returns the ID that the
// added worm was assigned, which starts at one and goes up from there.
//
MazeMap.prototype.addWorm = function addWorm( pStart, dLoopChance )
{
    if( this.pPlayer === null )
    {
        this.pPlayer = pStart;
        this.ePlayerSetup.emit();
    }
    else if( this.pGoal === null )
    {
        this.pGoal = pStart;
    }
    let iNewId = this.aWorms.length+1;
    this.aWorms.push(
        new Worm(
            iNewId,
            pStart,
            this,
            dLoopChance
            )
        );
    return iNewId;
}

//
// Worker function.  This calls the timestep funcion on each worm until they
// report that they are done working and have exhausted all possible moves.
//
// At the moment this function assumes we have 2 worms and connects them
// automatically once it's done running.
//
MazeMap.prototype.buildMaze = function buildMaze()
{
    do
    {
        for( let j = 0; j < this.aWorms.length; j++ )
        {
            if( !this.aWorms[j].timestep() )
            {
                this.aWorms.splice( j, 1 );
                j--;
            }
        }
    } while( this.aWorms.length > 0 );
    this.connect( 1, 2 );
}

//
// Connect the pathways created by two worms, specified by iWormId1 and
// iWormId2 to each other. this searches all walls in the maze and looks for
// a wall that seperates the path created by these two worms, then finds the
// wall that seperates the longest combined pathway between the two, and opens
// it up into a pathway.
//
MazeMap.prototype.connect = function connect( iWormId1, iWormId2 )
{
    let p = new Position( this.getDims() );
    let pMax1 = null;
    let pMax2 = null;
    let iDistMax = 0;
    let iDirMax = 0;

    let iDim = 0;
    for(;;)
    {
        let c = this.get( p );
        if( c.iPath === iWormId1 || c.iPath === iWormId2 )
        {
            // This cell is one of the two paths we want to connect, let's
            // see if there's a cell from the other path nearby.
            for( iDim = 0; iDim < this.getDims(); iDim++ )
            {
                // Look 'down' in the current dimension
                let t = p.translate( iDim, -1 );
                for( let iDir = 0; iDir < 2; iDir++ )
                {
                    // Is the current position inside the maze?
                    if( t.get( iDim ) >= 0 &&
                        t.get( iDim ) < this.getSize( iDim ) )
                    {
                        // Get cell here.
                        let c2 = this.get( t );
                        if( c.iPath !== c2.iPath &&
                            (c2.iPath === iWormId1 || c2.iPath === iWormId2 ) )
                        {
                            let iDist = c.iDist + c2.iDist;
                            if( iDist > iDistMax )
                            {
                                iDistMax = iDist;
                                pMax1 = p.copy();
                                pMax2 = t.copy();
                                iDirMax = iDim*2+iDir;
                            }
                        }
                    }

                    // Look the other direction
                    t.add( iDim, 2 );
                }
            }
        }

        // This is the rediculous engine that lets us iterate through
        // the entire maze, one cell at a time.  This basically increments our
        // position by one, but wraps at the edges of the maze.
        for( iDim = 0; iDim < this.getDims(); iDim++ )
        {
            let iNewVal = p.add( iDim, 1 );
            if( iNewVal < this.getSize( iDim ) )
                break;
            p.set( iDim, 0 );
        }

        // If we ran out of dimensions then it means that we hit the last
        // cell in the grid.
        if( iDim == this.getDims() )
            break;
    }

    this.get( pMax1 ).iWalls |= (1<<iDirMax);
    this.get( pMax2 ).iWalls |= (1<<oppositeDir(iDirMax));
}

/**
 * Class: Vector
 *
 * Simple helper class that stores a position and direction.
 *
 * @constructor
 */
function Vector( pPos, iDir )
{
    this.pPos = pPos;
    this.iDir = iDir;
}

/**
 * Class: Worm
 *
 * The main workhorse (workworm?) of maze generation.  The worm "eats" a path
 * through the maze. The basic algorithm works as follows:
 *   1. Search all directions around the current cell and list all unvisited
 *      cells, the previous cell that we came from, and all cells that we
 *      created but are seperated from our current position by a wall.
 *   2. If there are open cells, then we'll select one at random and travel to
 *      it, but first:
 *      2.a. If there are adjacent cells that we created, generate a random
 *           number and compare it to the loop threshold.  If it's smaller,
 *           then select an adjacent room at random and break through the wall
 *           to that room.
 *   3. If there are not open cells then travel back to the previous cell that
 *      we came from.  Start over from #1 in this cell.
 *   4. If we reach the starting position again, then bailout and consider our
 *      work done.
 * Every cell that a worm visits is marked with the worm's id (1 or greater),
 * and a distance value that increases by one for each cell away from the start
 * that we've traveled.  When backtracking we update our current distance so
 * that all distances are contiguous and increasing away from start.
 *
 * @constructor
 */
function Worm( iId, pStart, rMazeMap, dLoopChance )
{
    // Initialize basic state, we start with distance set to 1
    this.iId = iId;
    this.pPosition = pStart;
    this.rMazeMap = rMazeMap;
    this.iDist = 1;
    this.dLoopChance = dLoopChance;

    // Setup walls here to create an opening.  We're only going to do
    // this on the first two dimensions.  This assumes that we have at least
    // two dimensions, which I feel like is a safe assumption. 1d mazes are...
    // pretty easy.
    let iDirs = [];
    if( this.pPosition.get( 0 ) === 0 )
        iDirs.push( 1 );
    else if( this.pPosition.get( 0 ) === this.rMazeMap.getSize( 0 )-1 )
        iDirs.push( 2 );

    if( this.pPosition.get( 1 ) === 0 )
        iDirs.push( 4 );
    else if( this.pPosition.get( 1 ) === this.rMazeMap.getSize( 1 )-1 )
        iDirs.push( 8 );

    // Now that we know if we're near a wall in the first two demensions
    // do something with that
    if( iDirs.length > 0 )
    {
        // We are near a wall, pick a random wall to open a hole in
        this.rMazeMap.get(this.pPosition).iWalls |= iDirs[lRand.randInt(iDirs.length)];
        this.rMazeMap.get(this.pPosition).iPath = this.iId;
    }
}

//
// Perform one step as descirbed in the constructor.
//
Worm.prototype.timestep = function timestep()
{
    // Handy to reference how many dimensions we have
    let iDims = this.rMazeMap.getDims();

    // Possible directions
    let pDirs = [];
    let pLoopDirs;

    let cCur;
    for(;;)
    {
        cCur = this.rMazeMap.get( this.pPosition );
        let pBack = null;
        pLoopDirs = [];
        for( let j = 0; j < iDims; j++ )
        {
            let iSize = this.rMazeMap.getSize( j );
            let pPos = this.pPosition.translate( j, -1 );
            if( pPos.get( j ) >= 0 )
            {
                let xCell = this.rMazeMap.get( pPos );
                if( xCell.iPath === 0 )
                {
                    pDirs.push( new Vector( pPos, j*2 ) );
                }
                else if( xCell.iPath === this.iId &&
                        xCell.iDist === this.iDist-1 )
                {
                    pBack = pPos;
                }
                else if( (cCur.iWalls&(1<<(j*2))) === 0 &&
                    xCell.iPath === this.iId )
                {
                    pLoopDirs.push( new Vector( pPos, j*2 ) );
                }
            }

            pPos = this.pPosition.translate( j, 1 );
            if( pPos.get( j ) < iSize )
            {
                let xCell = this.rMazeMap.get( pPos );
                if( xCell.iPath === 0 )
                {
                    pDirs.push( new Vector( pPos, j*2+1 ) );
                }
                else if( xCell.iPath === this.iId &&
                        xCell.iDist === this.iDist-1 )
                {
                    pBack = pPos;
                }
                else if( (cCur.iWalls&(1<<(j*2+1))) === 0 &&
                    xCell.iPath === this.iId )
                {
                    pLoopDirs.push( new Vector( pPos, j*2+1 ) );
                }
            }
        }

        if( pDirs.length > 0 )
        {
            break;
        }
        else
        {
            if( pBack !== null )
            {
                this.pPosition = pBack;
                this.iDist--;
            }
            else
            {
                return false;
            }
        }
    }

    cCur = this.rMazeMap.get( this.pPosition );
    let iSel = lRand.randInt( pDirs.length );
    cCur.iWalls |= (1<<pDirs[iSel].iDir);
    let cNext = this.rMazeMap.get( pDirs[iSel].pPos );
    cNext.iWalls |= (1<<oppositeDir( pDirs[iSel].iDir ));
    cNext.iDist = ++this.iDist;
    cNext.iPath = this.iId;
    let oldPosition = this.pPosition;
    this.pPosition = pDirs[iSel].pPos;

    if( pLoopDirs.length > 0 && lRand.random() <= this.dLoopChance )
    {
        iSel = pLoopDirs[lRand.randInt( pLoopDirs.length )];
        cCur.iWalls |= (1<<iSel.iDir);
        cNext = this.rMazeMap.get( iSel.pPos );
        cNext.iWalls |= (1<<oppositeDir( iSel.iDir ));
    }

    return true;
}

/**
 * Class: Render
 *
 * Base class of render classes.  Doesn't do anything on it's own.
 *
 * @constructor
 */
function Render( rMazeMap, eMazeContainer )
{
    this.rMazeMap = rMazeMap;
    this.eMazeContainer = eMazeContainer;
}

//
// Empty base class function specifying that there should be a render function
// in child classes.
//
Render.prototype.render = function render()
{
}

/**
 * Class: RenderCanvas2D
 *
 * Our main render class.  This generates a single 2d slice of the current maze
 * on the "floor" that the player is currently on.  It also generates and
 * manages buttons you can use to interact with the maze.
 *
 * @constructor
 */
function RenderCanvas2D( rMazeMap, params ) // eMazeContainer, eUIContainer )
{
    let eMazeContainer = document.getElementById(params['maze']);
    let eUIContainer = document.getElementById(params['buttons']);
    let eReadoutBox = document.getElementById(params['readout']);

    Render.call( this, rMazeMap, eMazeContainer );
    this.rMazeMap.ePlayerMoved.connect(
        RenderCanvas2D.prototype.render.bind( this )
        );
    this.rMazeMap.ePlayerMoved.connect(
        RenderCanvas2D.prototype.updateButtons.bind( this )
        );
    this.rMazeMap.ePlayerMoved.connect(
        RenderCanvas2D.prototype.updateReadout.bind( this )
        );
    this.rMazeMap.eVictory.connect(
        RenderCanvas2D.prototype.setVictory.bind( this )
        );

    this.eCanvas = null;
    this.ctx = null;
    this.isSolved = false;

    this.pExtPosition = new Position( rMazeMap.getDims() );

    this.iIconSquare = Math.ceil(
        Math.sqrt((this.rMazeMap.getDims()-2)*2 + 1)
        );

    let iTargetSize = eMazeContainer.clientWidth;
    if( eMazeContainer.clientHeight !== 0 &&
        eMazeContainer.clientHeight < iTargetSize )
        iTargetSize = eMazeContainer.clientHeight;

    if( window.innerHeight < window.innerWidth )
    {
        // Portrait view
        if( iTargetSize === 0 )
            iTargetSize = window.innerHeight*0.9;
    }
    else
    {
        if( iTargetSize > window.innerHeight/2 )
            iTargetSize = window.innerHeight/2;
    }

    this.iBorder = 3;
    this.iIconSize = Math.floor(
        (
          (iTargetSize/this.rMazeMap.getSize( 0 )) -
          3 - (this.iIconSquare*3)
         )/this.iIconSquare
        );
    if( this.iIconSize > 15 )
        this.iIconSize = 15;
    else if( this.iIconSize < 5 )
        this.iIconSize = 5;

    this.iCellSize =
        this.iBorder +
        this.iIconSquare*(this.iIconSize+this.iBorder);
    
    this.eCanvas = document.createElement('canvas');
    this.eCanvas.width = this.iCellSize*this.rMazeMap.getSize( 0 );
    this.eCanvas.height = this.iCellSize*this.rMazeMap.getSize( 1 );
    eMazeContainer.appendChild( this.eCanvas );
    this.ctx = this.eCanvas.getContext("2d");
    this.ctx.lineWidth = 1.0;
    this.ctx.font = Math.ceil(this.iIconSize) + 'px sans serif';
    this.ctx.textBaseline = 'top';

    this.aMoveButtons = [];

    this.render();

    this.btnBox = eUIContainer;
    this.readoutBox = eReadoutBox;
    this.readoutNode = document.createTextNode('');
    this.readoutBox.appendChild( this.readoutNode );
    this.updateReadout();

    let cardTbl;
    let cardRow;
    let cardTd;

    cardTbl = document.createElement('table');
    cardRow = document.createElement('tr');
    cardTbl.appendChild( cardRow );
    cardRow.appendChild( document.createElement('td') );
    cardTd = document.createElement('td');
    this.aMoveButtons[2] = cardTd.appendChild(
        createMoveButton( this.rMazeMap, 1, -1, "North" )
        );
    cardRow.appendChild( cardTd );
    cardRow.appendChild( document.createElement('td') );
    if( this.rMazeMap.getDims() >= 3 )
    {
        cardTd = document.createElement('td');
        this.aMoveButtons[4] = cardTd.appendChild(
            createMoveButton( this.rMazeMap, 2, -1, "Up (^)" )
            );
        cardRow.appendChild( cardTd );
    }

    cardRow = document.createElement('tr');
    cardTbl.appendChild( cardRow );
    cardTd = document.createElement('td');
    this.aMoveButtons[0] = cardTd.appendChild(
        createMoveButton( this.rMazeMap, 0, -1, "West" )
        );
    cardRow.appendChild( cardTd );
    cardRow.appendChild( document.createElement('td') );
    cardTd = document.createElement('td');
    this.aMoveButtons[1] = cardTd.appendChild(
        createMoveButton( this.rMazeMap, 0, 1, "East" )
        );
    cardRow.appendChild( cardTd );
    if( this.rMazeMap.getDims() >= 3 )
    {
        cardRow.appendChild( document.createElement('td') );
    }
    
    cardRow = document.createElement('tr');
    cardTbl.appendChild( cardRow );
    cardRow.appendChild( document.createElement('td') );
    cardTd = document.createElement('td');
    this.aMoveButtons[3] = cardTd.appendChild(
        createMoveButton( this.rMazeMap, 1, 1, "South" )
        );
    cardRow.appendChild( cardTd );
    cardRow.appendChild( document.createElement('td') );
    if( this.rMazeMap.getDims() >= 3 )
    {
        cardTd = document.createElement('td');
        this.aMoveButtons[5] = cardTd.appendChild(
            createMoveButton( this.rMazeMap, 2, 1, "Down (v)" )
            );
        cardRow.appendChild( cardTd );
    }

    this.btnBox.appendChild( cardTbl );

    if( this.rMazeMap.getDims() >= 3 )
    {
        cardTbl = document.createElement('table');
        for( let j = 3; j < this.rMazeMap.getDims(); j++ )
        {
            cardRow = document.createElement('tr');
            cardTbl.appendChild( cardRow );

            cardTd = document.createElement('td');
            this.aMoveButtons[j*2] = cardTd.appendChild(
                createMoveButton( this.rMazeMap, j, -1, (j+1) + '-' )
                );
            cardRow.appendChild( cardTd );
            
            cardTd = document.createElement('td');
            this.aMoveButtons[j*2+1] = cardTd.appendChild(
                createMoveButton( this.rMazeMap, j, 1, (j+1) + '+' )
                );
            cardRow.appendChild( cardTd );
        }
        this.btnBox.appendChild( cardTbl );
    }

    this.updateButtons();
}

// Setup RenderCanvas2D as a child class of Render
RenderCanvas2D.prototype = Object.create(Render.prototype);
RenderCanvas2D.prototype.constructor = RenderCanvas2D;

//
// Performs the bulk of the work of resetting and rendering the maze. This is
// called whenever anything changes at all and the entire maze floor is redrawn.
//
// Since these are such simple graphics there's not much of an issue with this
// approach.  It could be optomized and only the parts that have changed could
// bo modified, but it's probably not worth it in the long run.  We're as
// likely to travel along any dimension as X or Y, and every dimension other
// than X and Y requrie a full redraw of the maze.
//
RenderCanvas2D.prototype.render = function render()
{
    let iSize = this.iCellSize;
    this.ctx.clearRect( 0, 0, this.eCanvas.width, this.eCanvas.height );
    this.ctx.beginPath();

    let p;
    if( this.rMazeMap.pPlayer === null )
        p = this.pExtPosition.copy();
    else
        p = this.rMazeMap.pPlayer.copy();

    let iPlayerIcon =
        Math.floor(this.iIconSquare*0.5) +
        Math.floor(this.iIconSquare*0.5) * this.iIconSquare;
    
    this.ctx.beginPath();
    this.ctx.strokeStyle = 'whitesmoke';
    for( let x = 0; x < this.rMazeMap.getSize( 0 ); x++ )
    {
        this.ctx.moveTo( x*iSize, 0 );
        this.ctx.lineTo( x*iSize, this.rMazeMap.getSize( 1 )*iSize );
    }
    for( let y = 0; y < this.rMazeMap.getSize( 1 ); y++ )
    {
        this.ctx.moveTo( 0, y*iSize );
        this.ctx.lineTo( this.rMazeMap.getSize( 0 )*iSize, y*iSize );
    }
    this.ctx.stroke();

    this.ctx.beginPath();
    this.ctx.strokeStyle = 'black';
    for( let x = 0; x < this.rMazeMap.getSize( 0 ); x++ )
    {
        for( let y = 0; y < this.rMazeMap.getSize( 1 ); y++ )
        {
            p.set( 0, x );
            p.set( 1, y );
            let c = this.rMazeMap.get( p );

            if( p.equals( this.rMazeMap.pGoal ) )
            {
                let oldStyle = this.ctx.fillStyle;
                this.ctx.fillStyle = 'palegreen';
                this.ctx.fillRect( x*iSize+2, y*iSize+2, iSize-4, iSize-4 );
                this.ctx.fillStyle = oldStyle;
            }

            if( (c.iWalls&1) === 0 && x === 0)
            {
                this.ctx.moveTo( x*iSize, y*iSize );
                this.ctx.lineTo( x*iSize, (y+1)*iSize );
            }
            if( (c.iWalls&2) === 0 )
            {
                this.ctx.moveTo( (x+1)*iSize, y*iSize );
                this.ctx.lineTo( (x+1)*iSize, (y+1)*iSize );
            }
            if( (c.iWalls&4) === 0 && y === 0)
            {
                this.ctx.moveTo( x*iSize, y*iSize );
                this.ctx.lineTo( (x+1)*iSize, y*iSize );
            }
            if( (c.iWalls&8) === 0 )
            {
                this.ctx.moveTo( x*iSize, (y+1)*iSize );
                this.ctx.lineTo( (x+1)*iSize, (y+1)*iSize );
            }

            // Extended dimenisons (above 2 :-P)
            let iIcon = 0;
            for( let ed = 2; ed < this.rMazeMap.getDims(); ed++ )
            {
                if( iIcon == iPlayerIcon )
                    iIcon++;
                if( (c.iWalls&(1<<(ed*2))) !== 0 )
                {
                    this.renderDirIcon( x, y, iIcon, ed*2 );
                }
                iIcon++;
                
                if( iIcon == iPlayerIcon )
                    iIcon++;
                if( (c.iWalls&(1<<(ed*2+1))) !== 0 )
                {
                    this.renderDirIcon( x, y, iIcon, ed*2+1 );
                }
                iIcon++;
            }
        }
    }
    this.ctx.stroke();

    // Draw the player
    if( this.rMazeMap.pPlayer !== null )
    {
        let bx = this.rMazeMap.pPlayer.get(0)*iSize +
            this.iBorder + Math.floor(iPlayerIcon%this.iIconSquare)*(this.iBorder+this.iIconSize);
        let by = this.rMazeMap.pPlayer.get(1)*iSize +
            this.iBorder + Math.floor(iPlayerIcon/this.iIconSquare)*(this.iBorder+this.iIconSize);
        this.rMazeMap.pPlayer.equals( p );
        this.ctx.beginPath();
        this.ctx.ellipse(
            bx+this.iIconSize*0.5, by+this.iIconSize*0.5,
            this.iIconSize*0.4, this.iIconSize*0.4,
            0,
            Math.PI*2.0,
            false
            );
        this.ctx.fill();
    }
}

//
// Helper function that draws the icons for the travel icons for dimensions
// after the first two.
//
RenderCanvas2D.prototype.renderDirIcon = function renderDirIcon(
    x, y, iIcon, iDir )
{
    let bx = x*this.iCellSize +
        this.iBorder +
        (iIcon%this.iIconSquare)*(this.iIconSize+this.iBorder);
    let by = y*this.iCellSize +
        this.iBorder +
        Math.floor(iIcon/this.iIconSquare)*(this.iIconSize+this.iBorder);

    //this.ctx.rect(bx, by, this.iIconSize, this.iIconSize );
    switch( iDir )
    {
        case 4:
            // Up
            this.ctx.moveTo(
                bx,
                by+this.iIconSize
                );
            this.ctx.lineTo(
                bx+this.iIconSize/2,
                by
                );
            this.ctx.lineTo(
                bx+this.iIconSize,
                by+this.iIconSize
                );
            break;

        case 5:
            // Down
            this.ctx.moveTo(
                bx,
                by
                );
            this.ctx.lineTo(
                bx+this.iIconSize/2,
                by+this.iIconSize
                );
            this.ctx.lineTo(
                bx+this.iIconSize,
                by
                );
            break;
        
        default:
            let label = 
                Math.floor((iDir/2.0)+1).toString() +
                (((iDir%2)===0)?'-':'+');
            this.ctx.fillText(
                label,
                bx, by
                );
            break;
    }
}

//
// Slot that updates the enabled/disabled status of the UI buttons after the
// player's position has changed.
//
RenderCanvas2D.prototype.updateButtons = function updateButtons()
{
    let c = this.rMazeMap.get( this.rMazeMap.pPlayer );
    for( let j = 0; j < this.rMazeMap.getDims()*2; j++ )
    {
        this.aMoveButtons[j].disabled = (c.iWalls&(1<<j)) === 0;
    }
}

//
// Slot that updates the textual readout label telling us what "floor" we're on
// when the player's position has changed.
//
RenderCanvas2D.prototype.updateReadout = function updateReadout()
{
    if( this.rMazeMap.getDims() <= 2 )
        return;

    let text = 'Floor: ' + (this.rMazeMap.pPlayer.get( 2 )+1);
    for( let j = 3; j < this.rMazeMap.getDims(); j++ )
    {
        text += ', ' + (this.rMazeMap.pPlayer.get( j )+1);
    }

    this.readoutNode.textContent = text;
}

//
// Slot that performs the operations needed to display that a victory has
// occured when the player has reached the exit.
//
RenderCanvas2D.prototype.setVictory = function setVictory()
{
    while( this.btnBox.hasChildNodes() )
    {
        this.btnBox.removeChild( this.btnBox.firstChild );
    }

    let h1 = document.createElement('h1');
    h1.appendChild(
        document.createTextNode('You win!')
        );
    this.btnBox.appendChild( h1 );
}

//
// Initialize
//

function lostInit( properties )
{
    let p = new Position( 4, [3, 3, 3, 3] );

    if( document.location.search !== '' )
    {
        let dat = document.location.search.slice(1);
        let datChunks = dat.split('&');
        for( let j = 0; j < datChunks.length; j++ )
        {
            let pair = datChunks[j].split('=');
            if( pair.length == 2 )
            {
                if( pair[0] == 'seed' )
                {
                    lRand.setSeed( parseInt( decodeURIComponent( pair[1] ), 10 ) );
                }
                else if( pair[0] == 'dims' )
                {
                    p = new Position( decodeURIComponent( pair[1] ) );
                }
            }
        }
    }

    let m = new MazeMap( p );
    let exit1 = new Position( p.getDims(), null );
    let exit2 = new Position( p.getDims(), null );
    exit2.set( 1, p.get( 1 )-1 );
    m.addWorm( exit1, 0.05 );
    m.addWorm( exit2, 0.05 );
    m.buildMaze();

    let eEditorBox = document.getElementById(properties['editor']);
    let eShareBox = document.getElementById(properties['share']);

    //let rend = new RenderCanvas2D( m, properties['render']['params'] );
    let rend = Reflect.construct(
        properties['render']['name'],
        [m, properties['render']['params']]
        );

    let formDiv = eEditorBox;
    let form = document.createElement('form');
    let dims = document.createElement('input');
    dims.name = 'dims';
    dims.value = p.toString();
    let sub = document.createElement('input');
    sub.type = 'submit';
    sub.value = 'New maze!';
    form.appendChild( dims );
    form.appendChild( document.createTextNode(' ') );
    form.appendChild( sub );
    formDiv.appendChild( form );

    let d = eShareBox;
    let dLink = document.createElement('a');
    let trgUrl = document.location.toString();
    let query = trgUrl.indexOf('?');
    if( query >= 0 )
    {
        trgUrl = trgUrl.substring(0, query);
    }
    trgUrl += '?seed=' + lRand.getSeed() + '&dims=' + p.toString();
    dLink.href = trgUrl;
    dLink.appendChild( document.createTextNode('Share this maze!') );
    d.appendChild(dLink);
}

// These are needed to export symbols we want to keep post minification
window['lostInit'] = lostInit;
window['RenderCanvas2D'] = RenderCanvas2D;